package com.chainyoung.component_tmtrade.ui.fragment.fiatcurrency;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Space;
import android.widget.TextView;

import com.chainyoung.common.appcommon.entity.CommonList;
import com.chainyoung.common.base.BaseFragment;
import com.chainyoung.common.common_widget.loadsir.LoadSirUtil;
import com.chainyoung.common.common_widget.loadsir.callback.Callback;
import com.chainyoung.common.common_widget.loadsir.core.LoadService;
import com.chainyoung.common.common_widget.loadsir.core.LoadSir;
import com.chainyoung.common.constant.LibConstant;
import com.chainyoung.common.custom_widget.EmptyCallback;
import com.chainyoung.common.custom_widget.EmptyCollectionCallback;
import com.chainyoung.common.custom_widget.LoadingCallback;
import com.chainyoung.common.custom_widget.PlaceholderCallback;
import com.chainyoung.common.custom_widget.RetryCallback;
import com.chainyoung.common.di.AppComponent;
import com.chainyoung.common.event.BaseEvent;
import com.chainyoung.common.utils.SPUtil;
import com.chainyoung.common.view.ActionSheetDialog;
import com.chainyoung.component_tmtrade.R;
import com.chainyoung.component_tmtrade.R2;
import com.chainyoung.component_tmtrade.bean.FiatCoin;
import com.chainyoung.component_tmtrade.bean.FiatOrder;
import com.chainyoung.component_tmtrade.di.component.DaggerTradeFiatCurrencyComponent;
import com.chainyoung.component_tmtrade.di.module.TradeFiatCurrencyModule;
import com.chainyoung.component_tmtrade.ui.adapter.TradeFiatCurrencyBuyAdapter;
import com.chainyoung.component_tmtrade.ui.adapter.TradeFiatCurrencyOrderAdapter;
import com.chainyoung.component_tmtrade.ui.mvp.contract.TradeFiatCurrencyOrderContract;
import com.chainyoung.component_tmtrade.ui.mvp.presenter.TradeFiatCurrencyOrderPresenter;
import com.chainyoung.component_tmtrade.ui.view.SelectOrderStatusWindow;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;


public class TradeFiatCurrencyOrderFragment extends BaseFragment<TradeFiatCurrencyOrderPresenter> implements TradeFiatCurrencyOrderContract.View {


    @BindView(R2.id.tv_select_order)
    TextView tvSelectOrder;
    @BindView(R2.id.rv_list)
    RecyclerView rvList;
    @BindView(R2.id.refresh_layout)
    SmartRefreshLayout refreshLayout;


    private LoadService loadService;
    private String coinName;


    /**
     * 当前订单
     */
    public static final String ORDER_CURRENT = "curr";
    /**
     * 历史订单
     */
    public static final String ORDER_HISTORY = "history";


    private TradeFiatCurrencyOrderAdapter mAdapter;

    private List<FiatOrder> mData = new ArrayList<>();
    private boolean isCanloadMore;
    private int pageNo = 1;
    private boolean isFirst = true;
    private String listType;//当前订单和历史订单

    private List<String> statusList = new ArrayList<>();
    private List<Integer> status = new ArrayList<>();

    public static TradeFiatCurrencyOrderFragment newInstance(String list_type) {
        TradeFiatCurrencyOrderFragment fragment = new TradeFiatCurrencyOrderFragment();
        Bundle args = new Bundle();
        args.putString("list_type", list_type);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerTradeFiatCurrencyComponent.builder()
                .appComponent(appComponent)
                .tradeFiatCurrencyModule(new TradeFiatCurrencyModule(this))
                .build()
                .inject(this);
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (getArguments() != null) {
            listType = getArguments().getString("list_type");
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initUi() {
        super.initUi();
        initStatusList();

        coinName = getString(R.string.tmtrade_fiat_currency);
        mAdapter = new TradeFiatCurrencyOrderAdapter(mData);
        rvList.setAdapter(mAdapter);
        rvList.setLayoutManager(new LinearLayoutManager(mContext));
        DividerItemDecoration itemDecoration = new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL);
        itemDecoration.setDrawable(ContextCompat.getDrawable(mContext, R.drawable.shape_divider_gray));
        rvList.addItemDecoration(itemDecoration);

        mAdapter.notifyDataSetChanged();
        refreshLayout.setEnableLoadMore(false);


        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isCanloadMore) {
                    pageNo++;
                    loadData();
                } else {
                    refreshLayout.finishLoadMore();
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageNo = 1;
                loadData();
            }
        });

        LoadSir loadSir = new LoadSir.Builder()
                .addCallback(new LoadingCallback())
                .addCallback(new EmptyCallback())
                .addCallback(new RetryCallback())
                .setDefaultCallback(LoadingCallback.class)
                .build();
        loadService = loadSir.register(refreshLayout, new Callback.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadService.showCallback(LoadingCallback.class);
                pageNo = 1;
                loadData();
            }
        });

    }

    private void initStatusList() {
        switch (listType) {
            case ORDER_CURRENT:
                statusList.add(mContext.getString(R.string.tmtrade_all));
                statusList.add(mContext.getString(R.string.tmtrade_order_wait_for_pay));
                statusList.add(mContext.getString(R.string.tmtrade_order_already_payed));
                statusList.add(mContext.getString(R.string.tmtrade_wait_for_recieve));
                status.add(-1);
                status.add(10);
                status.add(7);
                status.add(8);
                break;
            case ORDER_HISTORY:
                statusList.add(mContext.getString(R.string.tmtrade_all));
                statusList.add(mContext.getString(R.string.tmtrade_order_finished));
                statusList.add(mContext.getString(R.string.tmtrade_order_closed));
                status.add(-1);
                status.add(1);
                status.add(234);
                break;
        }

    }


    @Override
    protected void onFirstUserVisible() {
        pageNo = 1;
        loadData();

    }

    @Override
    public void onUserVisible() {
        super.onUserVisible();
        pageNo = 1;
        loadData();
    }

    private void loadData() {
        TreeMap<String, Object> map = new TreeMap<>();
        map.put("token", SPUtil.getString(LibConstant.TOKEN));
        map.put("page", pageNo);
        map.put("limit", LibConstant.PAGE_SIZ);
        map.put("list_type", listType);
        if (orderStatus != -1) {
            map.put("status", orderStatus);
        }
        map.put("coin", coinName.toLowerCase());
        mPresenter.getOrderList(map);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.tmtrade_fragment_current_order;
    }


    private SelectOrderStatusWindow popupWindow;
    private int orderStatus = -1;

    @OnClick(R2.id.tv_select_order)
    void showOrderStatusList() {
        switch (listType) {
            case ORDER_CURRENT:
                new ActionSheetDialog(mContext).builder().setCancelable(true).setCanceledOnTouchOutside(true).
                        addSheetItem(statusList.get(0), ActionSheetDialog.SheetItemColor.Blue, onSheetItemClickListener).
                        addSheetItem(statusList.get(1), ActionSheetDialog.SheetItemColor.Blue, onSheetItemClickListener).
                        addSheetItem(statusList.get(2), ActionSheetDialog.SheetItemColor.Blue, onSheetItemClickListener).
                        addSheetItem(statusList.get(3), ActionSheetDialog.SheetItemColor.Blue, onSheetItemClickListener).
                        show();
                break;
            case ORDER_HISTORY:
                new ActionSheetDialog(mContext).builder().setCancelable(true).setCanceledOnTouchOutside(true).
                        addSheetItem(statusList.get(0), ActionSheetDialog.SheetItemColor.Blue, onSheetItemClickListener).
                        addSheetItem(statusList.get(1), ActionSheetDialog.SheetItemColor.Blue, onSheetItemClickListener).
                        addSheetItem(statusList.get(2), ActionSheetDialog.SheetItemColor.Blue, onSheetItemClickListener).
                        show();
                break;
        }

    }

    ActionSheetDialog.OnSheetItemClickListener onSheetItemClickListener = new ActionSheetDialog.OnSheetItemClickListener() {
        @Override
        public void onClick(int which) {
            orderStatus = status.get(which - 1);
            tvSelectOrder.setText(statusList.get(which - 1));
            pageNo = 1;
            loadData();
        }
    };


    @Override
    public void onGetOrderListSuccess(CommonList<FiatOrder> data) {
        refreshLayout.finishLoadMore();
        refreshLayout.finishRefresh();
        if (data == null) {
            isCanloadMore = false;
            refreshLayout.setEnableLoadMore(false);
            return;

        }
        if (pageNo == 1) {
            mData.clear();
        }
        if (data.getList() != null) {
            mData.addAll(data.getList());
        }
        if (data.getList() == null || data.getList().size() < LibConstant.PAGE_SIZ) {
            isCanloadMore = false;
            refreshLayout.setEnableLoadMore(false);
        } else {
            isCanloadMore = true;
            refreshLayout.setEnableLoadMore(true);
        }
        if (mData.isEmpty()) {
            loadService.showCallback(EmptyCallback.class);
        } else {
            loadService.showSuccess();
        }
        mAdapter.notifyDataSetChanged();


    }

    @Override
    public void onGetOrderListFailed() {
        refreshLayout.finishLoadMore();
        refreshLayout.finishRefresh();
        loadService.showCallback(RetryCallback.class);
    }

    @Subscriber
    void onRefreshCoinName(BaseEvent event) {
        if (event.getCode().equals(BaseEvent.EventCode.REFRESH_FIAT_COIN_NAME)) {
            FiatCoin fiatCoin = (FiatCoin) event.getData();
            coinName=fiatCoin.getKey();
            if (getUserVisibleHint()) {
                pageNo = 1;
                loadData();
            }
        }
    }



}
